package gui.Packaging;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.Properties;

import javax.mail.MessageAware;
import javax.swing.JTabbedPane;
import javax.swing.JPanel;

import net.miginfocom.swing.MigLayout;

import javax.swing.Action;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.plaf.basic.BasicBorders.RadioButtonBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.TabExpander;

import clients.RPCClient;

import java.awt.GridLayout;

import javax.swing.JButton;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

import javax.swing.SwingConstants;

import java.awt.Font;
import java.awt.FlowLayout;

import javax.swing.JSplitPane;
import javax.swing.JSeparator;

import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.RowSpec;

import javax.swing.SpringLayout;

import org.apache.log4j.spi.LocationInfo;
import org.apache.poi.hdf.extractor.NewOleFile;
import org.apache.poi.ss.formula.atp.DateParser;
import org.jdatepicker.impl.JDatePanelImpl;
import org.jdatepicker.impl.JDatePickerImpl;
import org.jdatepicker.impl.UtilDateModel;

import utilities.DateLabelFormatter;
import utilities.Services;

import javax.swing.BoxLayout;
import javax.swing.JTextPane;
import javax.swing.JFormattedTextField;

import java.awt.Color;

import javax.swing.JComboBox;
import javax.swing.JToolBar;
import javax.swing.border.BevelBorder;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EtchedBorder;

import com.jgoodies.forms.factories.FormFactory;
import com.rabbitmq.client.AMQP.Confirm.Select;

import entities.PolishReportEntity;

import java.awt.ComponentOrientation;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;

import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.border.LineBorder;
import javax.swing.border.MatteBorder;
import javax.swing.border.SoftBevelBorder;

import java.awt.CardLayout;
import java.awt.BorderLayout;

import javax.swing.UIManager;
import javax.swing.border.TitledBorder;
import javax.swing.JScrollBar;
import javax.swing.JToggleButton;
import javax.swing.JCheckBox;
import javax.swing.JRadioButton;

import java.awt.Choice;
import java.awt.List;
import java.awt.Canvas;

import javax.swing.JTree;

import java.awt.Scrollbar;

import javax.swing.JMenu;

import java.awt.Checkbox;

import javax.swing.JSlider;

import java.awt.event.InputMethodListener;
import java.awt.event.InputMethodEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeEvent;
import java.awt.TextField;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.TextListener;
import java.awt.event.TextEvent;
import java.beans.VetoableChangeListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;

import jxl.format.Orientation;

import javax.swing.ImageIcon;

import java.awt.TextArea;

import javax.swing.JTextArea;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JTextField;

import java.awt.SystemColor;
/**
 * 
 * @author adam
 *Packaging first tabbed pane , holds the frame and the panel in it . 
 */
public class JTappedPanePackagingMain extends JTabbedPane {
	private RPCClient myRPCClient;
	private JTable table;
	private DefaultTableModel model ;
	private int rowSetected;
	private int columnSelected;
	private RPCClient myPackagingCleint;
	private PackagingFrame myPackagingFrame;
	private JTappedPanePackagingMain myJTappedPanePackagingMain;
	private JDatePickerImpl jDatePicker;
	private JPanel panel;
	private JPanel panel_1;
	private JDatePickerImpl datePickerB;
	private JDatePickerImpl datePickerA;
	private JTextPane OrderIDAtextPane;
	private JComboBox employeeComboBoxB;
	private JComboBox employeeComboBoxA;
	private String dateIsSetA=null;
	private String dateIsSetB=null;
	private String quantityToPackA=null;
	private String quantityToPackB=null;
	private TextField jtf_quantityToPackB;
	private TextField jtf_quantityToPackA;
	private String employeeNameSelectedA;
	private String employeeNameSelectedB;
	private JTappedPanePackagingMain myJTappedPane;
	private JTextPane OrderIDBtextPane;
	private TextField totalQuantityB;
	private TextField totalQuantityA;
	private JRadioButton radioA;
	private JRadioButton radioB;
	private JTextArea commentsTextAreaA;
	private JTextArea commentsTextAreaB;
	private JTextField hashmashaTextFieldB;
	private JTextField hashmashaTextFieldA;
	private JTextField newQuantityB;
	private JTextField newQuantityA;
	private JTextField diopterB;
	private JTextField diopterA;
	private JComboBox typeA;
	private JComboBox typeB;
	private Boolean finishPackagingChlicked ;

/**
 * Constructor	
 * @param frame-PackagingFrame
 */
	public JTappedPanePackagingMain(PackagingFrame frame) 
	{
		setBackground(new Color(173, 216, 230));
		setBorder(new TitledBorder(null, "", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		employeeComboBoxA = new JComboBox();
		employeeComboBoxB = new JComboBox();
		finishPackagingChlicked = false;
		
		try
		{
			myRPCClient = new RPCClient();
		} catch (Exception e1) {
			e1.printStackTrace();
			// Failed to get list
    		JOptionPane.showMessageDialog(frame,
				    "שגיאה בחיבור לשרת","שגיאה",JOptionPane.ERROR_MESSAGE);
		//	System.out.println("ERROR - src-> Packaging->JTappedPanePackaging -> Constructor Error trying to connect to RPCCleint ");
		}
		myJTappedPane= this;
		myPackagingFrame=frame;
		 
		myJTappedPanePackagingMain = this;
		panel = new JPanel(){@Override
			public void paintComponent(Graphics g) {
	        Graphics2D g2d = (Graphics2D) g;
	        Color color1 = getBackground();
	        Color color2 = color1.darker();
	        int w = getWidth();
	        int h = getHeight(); 
	        GradientPaint gp = new GradientPaint(
	                0, 0, color1,
	                0, h, color2);

	        g2d.setPaint(gp);
	        g2d.fillRect(0, 0, w, h);
	        }};
		panel.setBorder(new TitledBorder(null, "", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		panel.setBackground(new Color(173, 216, 230));
		//
		ImageIcon listOfOrdersTab = new ImageIcon(PackagingFrame.class.getResource("/graphics/listoforders.png"));
		//
		
		addTab("רשימת פקע''ות לאריזה", listOfOrdersTab, panel);
		
		panel.setLayout(new MigLayout("", "[][grow][]", "[][grow][][][]"));
		
		this.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
		JLabel label = new JLabel("מחלקת-אריזה");
		label.setFont(new Font("Tahoma", Font.PLAIN, 13));
		panel.add(label, "cell 1 0,alignx center");
		
		JScrollPane scrollPane = new JScrollPane();
		panel.add(scrollPane, "flowx,cell 1 1,alignx center,growy");
		
		table = new JTable();
		table.setFont(new Font("Tahoma", Font.PLAIN, 13));
		
		table.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				// need to move to the other window with the orderID information 
				rowSetected = table.getSelectedRow();
			//	System.out.println(rowSetected);
				myJTappedPane.setSelectedIndex(1);
				OrderIDAtextPane.setText(model.getValueAt(Integer.valueOf(rowSetected),0).toString());
				OrderIDBtextPane.setText(model.getValueAt(Integer.valueOf(rowSetected),0).toString());
				try{
					// Setting stepA total quantity
					myRPCClient = new RPCClient();
					ArrayList<Object>message = new ArrayList<>();
					ArrayList<Object>respond = new ArrayList<>();
					message.add("getOrderIDQuantity");
					message.add(OrderIDAtextPane.getText().toString());
					message.add("1");
					respond = myRPCClient.call(message);
					if(respond.get(1).toString().equalsIgnoreCase("valid"))
					{
						totalQuantityA.setText(respond.get(2).toString());
					}else{
						//something is wrong
					}
					// Setting stepB total quantity
					message.clear();
					respond.clear();
					message.add("getOrderIDQuantity");
					message.add(OrderIDAtextPane.getText().toString());
					message.add("2");
					respond = myRPCClient.call(message);
					if(respond.get(1).toString().equalsIgnoreCase("valid"))
					{
						totalQuantityB.setText(respond.get(2).toString());
					}else{
						//something is wrong
					}
					
				}catch(Exception e)
				{
					//e.printStackTrace();
				}
				int totalA = Integer.valueOf(totalQuantityA.getText().toString()); 
				int totalB = Integer.valueOf(totalQuantityB.getText().toString());
				if(totalA <0)
				{
					totalQuantityA.setText("0");
				}
				if(totalB <0)
				{
					totalQuantityB.setText("0");
				}
			}
		});
		table.setModel(new DefaultTableModel(
			new Object[][] {
			},
			new String[] {
				"\u05DE\u05E1\u05E4\u05E8 \u05E4\u05E7\"\u05E2"
			}
		));
		scrollPane.setViewportView(table);
		model = (DefaultTableModel) table.getModel();
		JButton button = new JButton("יציאה");
		button.setFont(new Font("Tahoma", Font.PLAIN, 13));
		button.setIcon(new ImageIcon(JTappedPanePackagingMain.class.getResource("/graphics/exit.png")));
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0)
			{
				Object[] options = {"כן","לא"};
        		int n = JOptionPane.showOptionDialog(myPackagingFrame, "האם ברצונך לצאת מהמערכת?","אישור יציאה", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options,"");
        		
        		if (n==0)
        		{
        			if (myRPCClient != null)
                    {
                      try
                      {
                    	  myRPCClient.close();
                      }
                      catch (Exception ignore)
                      {}
                     }
            		
            		System.exit(0);
        		}
			}
		});
		
		JButton button_2 = new JButton("רענן");
		button_2.setFont(new Font("Tahoma", Font.PLAIN, 13));
		button_2.setIcon(new ImageIcon(JTappedPanePackagingMain.class.getResource("/graphics/refreshOrders.png")));
		button_2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				try{
					ArrayList<Object>message = new ArrayList<>();
					ArrayList<Object>respond = new ArrayList<>();
					myPackagingCleint = new RPCClient();
					message.add("initializePackageMailPanelVariables");
					respond = myPackagingCleint.call(message);
					if(respond.get(1).toString().equalsIgnoreCase("valid"))
					{
						setVairables(respond);
					}
					else
					{
						// Failed to get list
	            		JOptionPane.showMessageDialog(frame,
							    "שגיאה בחיבור לשרת","שגיאה",JOptionPane.ERROR_MESSAGE);
					//	System.out.println("no GOOD");
					}
				}catch(Exception e)
				{
					//e.printStackTrace();
				}
			}
		});
		panel.add(button_2, "cell 1 2,alignx right,aligny top");
		panel.add(button, "flowx,cell 1 4,alignx center");
		scrollPane.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				
				
			}
		});
		
		
		panel_1 = new JPanel(){@Override
			public void paintComponent(Graphics g) {
	        Graphics2D g2d = (Graphics2D) g;
	        Color color1 = getBackground();
	        Color color2 = color1.darker();
	        int w = getWidth();
	        int h = getHeight(); 
	        GradientPaint gp = new GradientPaint(
	                0, 0, color1,
	                0, h, color2);

	        g2d.setPaint(gp);
	        g2d.fillRect(0, 0, w, h);
	        }};
		panel_1.setBackground(new Color(173, 216, 230));
		panel_1.setBorder(new TitledBorder(null, "", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		ImageIcon packgaingReportTab = new ImageIcon(PackagingFrame.class.getResource("/graphics/packagingReport.png"));
		addTab("דוח אריזה", packgaingReportTab, panel_1);
		
		
		//Setting up Date pickers 
		UtilDateModel startmodel = new UtilDateModel();
		UtilDateModel endmodel = new UtilDateModel();
		
		
		
		Properties p = new Properties();
		p.put("text.today", "היום");
		p.put("text.month", "חודש");
		p.put("text.year", "שנה");
		JDatePanelImpl startPanel = new JDatePanelImpl(startmodel, p);
		JDatePanelImpl endPanel = new JDatePanelImpl(endmodel, p);
		panel_1.setLayout(new MigLayout("", "[grow][][][][grow]", "[grow][][][][grow]"));
		
		JPanel panel_2 = new JPanel(){@Override
			public void paintComponent(Graphics g) {
	        Graphics2D g2d = (Graphics2D) g;
	        Color color1 = getBackground();
	        Color color2 = color1.darker();
	        int w = getWidth();
	        int h = getHeight(); 
	        GradientPaint gp = new GradientPaint(
	                0, 0, color1,
	                0, h, color2);

	        g2d.setPaint(gp);
	        g2d.fillRect(0, 0, w, h);
	        }};
		panel_2.setBackground(new Color(173, 216, 230));
		panel_2.setBorder(new TitledBorder(null, "\u05D0\u05E8\u05D9\u05D6\u05D4 \u05D1", TitledBorder.CENTER, TitledBorder.TOP, null, null));
		panel_1.add(panel_2, "cell 1 1,grow");
		
		JLabel label_5 = new JLabel("תאריך אריזה:");
		panel_2.setLayout(new MigLayout("", "[grow][][][grow]", "[14px][20px][14px][23px][15px][20px][20px][46px,grow][][grow][]"));
		
		OrderIDBtextPane = new JTextPane();
		OrderIDBtextPane.setEditable(false);
		OrderIDBtextPane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
		panel_2.add(OrderIDBtextPane, "cell 1 1,alignx center,aligny top");
		JLabel label_4 = new JLabel("מספר פק\"ע:");
		panel_2.add(label_4, "cell 2 1,alignx left,aligny bottom");
		datePickerB = new JDatePickerImpl(startPanel, new DateLabelFormatter());
		datePickerB.setBackground(new Color(173, 216, 230));
		datePickerB.addFocusListener(new FocusAdapter() {
			@Override
			public void focusLost(FocusEvent e) {
				dateIsSetB = datePickerB.getJFormattedTextField().getText().toString();
			//	System.out.println("Property changed - dateIsSetB :'"+dateIsSetB+"'");
			}
		});
		datePickerB.getJFormattedTextField().addFocusListener(new FocusAdapter() {
			@Override
			public void focusLost(FocusEvent arg0) {
				dateIsSetB = datePickerB.getJFormattedTextField().getText().toString();
			//	System.out.println("Property changed - dateIsSetB :'"+dateIsSetB+"'");
			}
		});
		datePickerB.getJFormattedTextField().addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				dateIsSetB = datePickerB.getJFormattedTextField().getText().toString();
			//	System.out.println("Property changed - dateIsSetB :'"+dateIsSetB+"'");
			}
		});
		datePickerB.getJFormattedTextField().addPropertyChangeListener(new PropertyChangeListener() {
			public void propertyChange(PropertyChangeEvent arg0) {
				dateIsSetB = datePickerB.getJFormattedTextField().getText().toString();
			//	System.out.println("Property changed - dateIsSetB :'"+dateIsSetB+"'");
			}
		});
		datePickerB.getJFormattedTextField().setHorizontalAlignment(SwingConstants.CENTER);
		panel_2.add(datePickerB, "cell 1 2,alignx center,aligny top");
		
		JLabel label_10 = new JLabel("סה\"כ  /   כמה");
		label_10.setHorizontalAlignment(SwingConstants.CENTER);
		panel_2.add(label_10, "cell 1 4,alignx center,aligny bottom");
		
		jtf_quantityToPackB = new TextField();
		jtf_quantityToPackB.addTextListener(new TextListener() {
			public void textValueChanged(TextEvent arg0) {
				quantityToPackB = jtf_quantityToPackB.getText().toString();
			//	System.out.println("jtf_quantityToPackB is : '"+quantityToPackB+"'");
			}
		});
		jtf_quantityToPackB.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent arg0) {
				
			}
		});
		
		JLabel label_8 = new JLabel("ארזתי\\פסלתי:");
		panel_2.add(label_8, "cell 2 4,alignx left,aligny top");
		panel_2.add(jtf_quantityToPackB, "flowx,cell 1 5,alignx center");
		
		JLabel label_11 = new JLabel("/");
		label_11.setHorizontalAlignment(SwingConstants.CENTER);
		panel_2.add(label_11, "cell 1 5,alignx center,aligny top");
		
		totalQuantityB = new TextField();
		totalQuantityB.setEditable(false);
		panel_2.add(totalQuantityB, "cell 1 5,alignx center");
		panel_2.add(label_5, "cell 2 2 2 1,alignx left,aligny top");
		
		
		employeeComboBoxB.addPropertyChangeListener(new PropertyChangeListener() {
			public void propertyChange(PropertyChangeEvent evt) {
				if(employeeComboBoxB.getSelectedItem()!=null)
				{
					employeeNameSelectedB = employeeComboBoxB.getSelectedItem().toString();
				//	System.out.println("employeeComboBoxB is : '"+employeeNameSelectedB+"'");
				}
			}
		});
		panel_2.add(employeeComboBoxB, "cell 1 6,alignx right,aligny top");
		
		JLabel label_14 = new JLabel("עובד:");
		label_14.setHorizontalAlignment(SwingConstants.CENTER);
		panel_2.add(label_14, "cell 2 6,alignx left,aligny top");
		
		JScrollPane scrollPane_2 = new JScrollPane();
		panel_2.add(scrollPane_2, "cell 1 7,grow");
		
		commentsTextAreaB = new JTextArea();
		commentsTextAreaB.setEnabled(false);
		commentsTextAreaB.setWrapStyleWord(true);
		scrollPane_2.setViewportView(commentsTextAreaB);
		commentsTextAreaB.setText("הערות להשמשה/פסילה");
		
		JLabel label_16 = new JLabel("הערות:");
		panel_2.add(label_16, "cell 2 7,aligny top");
		
		JPanel panel_4 = new JPanel(){@Override
			public void paintComponent(Graphics g) {
	        Graphics2D g2d = (Graphics2D) g;
	        Color color1 = getBackground();
	        Color color2 = color1.darker();
	        int w = getWidth();
	        int h = getHeight(); 
	        GradientPaint gp = new GradientPaint(
	                0, 0, color1,
	                0, h, color2);

	        g2d.setPaint(gp);
	        g2d.fillRect(0, 0, w, h);
	        }};
		panel_4.setBackground(new Color(173, 216, 230));
		panel_4.setBorder(new TitledBorder(null, "\u05D4\u05E9\u05DE\u05E9\u05D4", TitledBorder.RIGHT, TitledBorder.TOP, null, null));
		panel_2.add(panel_4, "cell 1 10,grow");
		panel_4.setLayout(new MigLayout("", "[][][grow][][grow][][][grow][grow][][][]", "[][][][]"));
		
		hashmashaTextFieldB = new JTextField();
		panel_4.add(hashmashaTextFieldB, "cell 0 0 11 1");
		hashmashaTextFieldB.setColumns(10);
		hashmashaTextFieldB.setEnabled(false);
		
		JLabel label_19 = new JLabel("מספר פקע חדש להשמשה:");
		panel_4.add(label_19, "cell 11 0");
		
		typeB = new JComboBox();
		panel_4.add(typeB, "cell 0 1 11 1,growx");
		
		JLabel label_20 = new JLabel("סוג:");
		panel_4.add(label_20, "cell 11 1");
		
		newQuantityB = new JTextField();
		newQuantityB.setEnabled(false);
		panel_4.add(newQuantityB, "cell 0 2 11 1,growx");
		newQuantityB.setColumns(10);
		
		JLabel label_21 = new JLabel("כמות:");
		panel_4.add(label_21, "cell 11 2");
		
		diopterB = new JTextField();
		panel_4.add(diopterB, "cell 0 3 11 1,growx");
		diopterB.setColumns(10);
		
		JLabel label_25 = new JLabel("דיופטר:");
		panel_4.add(label_25, "cell 11 3");
		typeB.setEnabled(false);
		diopterB.setEnabled(false);
		
		JPanel panel_6 = new JPanel(){@Override
			public void paintComponent(Graphics g) {
	        Graphics2D g2d = (Graphics2D) g;
	        Color color1 = getBackground();
	        Color color2 = color1.darker();
	        int w = getWidth();
	        int h = getHeight(); 
	        GradientPaint gp = new GradientPaint(
	                0, 0, color1,
	                0, h, color2);

	        g2d.setPaint(gp);
	        g2d.fillRect(0, 0, w, h);
	        }};
		panel_6.setBackground(new Color(173, 216, 230));
		panel_6.setBorder(new BevelBorder(BevelBorder.RAISED, new Color(224, 255, 255), new Color(224, 255, 255), new Color(173, 216, 230), new Color(173, 216, 230)));
		panel_1.add(panel_6, "cell 2 1,alignx center,growy");
		panel_6.setLayout(new MigLayout("", "[][][]", "[][][][][][][][][][][]"));
		
		JComboBox comboBoxOperationToDo = new JComboBox();
		panel_6.add(comboBoxOperationToDo, "cell 0 0");
		comboBoxOperationToDo.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
		comboBoxOperationToDo.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if(comboBoxOperationToDo.getSelectedItem().toString().equalsIgnoreCase("השמשה") || comboBoxOperationToDo.getSelectedItem().toString().equalsIgnoreCase("פסילה"))
				{
					commentsTextAreaA.setEnabled(true);
					commentsTextAreaA.setText("");
					commentsTextAreaB.setEnabled(true);
					commentsTextAreaB.setText("");
					
				}
				else{
					commentsTextAreaA.setEnabled(false);
					commentsTextAreaB.setEnabled(false);
				}
				if(comboBoxOperationToDo.getSelectedItem().toString().equalsIgnoreCase("השמשה"))
				{
					hashmashaTextFieldA.setEnabled(true);
					hashmashaTextFieldB.setEnabled(true);
					newQuantityA.setEnabled(true);
					newQuantityB.setEnabled(true);
					typeA.setEnabled(true);
					typeB.setEnabled(true);
					diopterA.setEnabled(true);
					diopterB.setEnabled(true);
					jtf_quantityToPackA.setText("");
					jtf_quantityToPackB.setText("");
					jtf_quantityToPackA.setEnabled(false);
					jtf_quantityToPackB.setEnabled(false);
					
				}
				else
				{
					hashmashaTextFieldA.setEnabled(false);
					hashmashaTextFieldB.setEnabled(false);
					newQuantityA.setEnabled(false);
					newQuantityB.setEnabled(false);
					typeA.setEnabled(false);
					typeB.setEnabled(false);
					diopterA.setEnabled(false);
					diopterB.setEnabled(false);	
					jtf_quantityToPackA.setEnabled(true);
					jtf_quantityToPackB.setEnabled(true);
				}
				
			}
		});
		comboBoxOperationToDo.setModel(new DefaultComboBoxModel(new String[] {"אריזה", "השמשה", "פסילה", "סיום אריזה"}));
		
		JLabel label_18 = new JLabel("פעולה לבחירה :");
		panel_6.add(label_18, "cell 2 0");
		radioB = new JRadioButton("אריזה ב");
		panel_6.add(radioB, "cell 0 2,alignx center");
		radioB.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(radioB.isSelected())
					radioA.setSelected(false);
				else
					radioA.setSelected(true);
			}
		});
		radioA = new JRadioButton("אריזה א");
		panel_6.add(radioA, "cell 2 2,alignx center");
		radioA.setSelected(true);
		// END initializing A\B type Combo boxes
									JButton button_1 = new JButton("בצע");
									button_1.setIcon(new ImageIcon(JTappedPanePackagingMain.class.getResource("/graphics/apply.png")));
									panel_6.add(button_1, "cell 1 4,alignx center");
									button_1.addActionListener(new ActionListener() {
										public void actionPerformed(ActionEvent arg0) {
											ArrayList<Object>message = new ArrayList<>();
											ArrayList<Object>respond = new ArrayList<>();
											String packageID;
				if(comboBoxOperationToDo.getSelectedItem().toString().equalsIgnoreCase("אריזה"))
						{
							if(radioA.isSelected())
							{
								dateIsSetA= datePickerA.getJFormattedTextField().getText().toString();
								if((dateIsSetA == null) || (quantityToPackA == null) || (dateIsSetA.equalsIgnoreCase(""))|| quantityToPackA.equals("") )
								{
									JOptionPane.showMessageDialog(myPackagingFrame, "מלא את כל השדות הנחוצים", "שגיאה", JOptionPane.ERROR_MESSAGE);
								}
								else
								{
									if(Services.isNumeric(quantityToPackA)==true)
									{
											int quantityToPackAINT = Integer.valueOf(quantityToPackA);
											int totalA = Integer.valueOf(totalQuantityA.getText().toString());
											if(quantityToPackAINT <= totalA && quantityToPackAINT!=0)
											{
													message.add("checkExistingRowPackagingReport");
													message.add(OrderIDAtextPane.getText().toString()); //orderID
													message.add(employeeComboBoxA.getSelectedItem().toString()); //employee name
													message.add("1");
													try{
														respond = myRPCClient.call(message);
														if(respond.get(1).toString().equalsIgnoreCase("unvalid"))	//there is no row in packagereport ,need to create new row
														{
															//String packageID = respond.get(2).toString();
															message.clear();
															message.add("addNewPackageReport");
															message.add(OrderIDAtextPane.getText().toString()); // orderID
															message.add(dateIsSetA);
															message.add(quantityToPackA);
															message.add(employeeComboBoxA.getSelectedItem().toString());
															message.add("1");
															
															respond.clear();
															respond = myRPCClient.call(message);
															if(respond.get(1).toString().equalsIgnoreCase("valid"))
															{
																JOptionPane.showMessageDialog(myPackagingFrame, "בוצעה אריזה"); 
																respond.clear();
																message.clear();
																message.add("getOrderIDQuantity");
																message.add(OrderIDAtextPane.getText().toString());
																message.add("1");
																respond = myRPCClient.call(message);
																if(respond.get(1).toString().equalsIgnoreCase("valid"))
																{
																	totalQuantityA.setText(respond.get(2).toString());
																}else{
																	//something is wrong
																}
																
																jtf_quantityToPackA.setText("");
																datePickerA.getJFormattedTextField().setText("");
																quantityToPackA=null;
																//dateIsSetA=null;
																commentsTextAreaA.setText("");									}
															else
															{
																JOptionPane.showMessageDialog(myPackagingFrame, "לא בוצעה אריזה"); 
															}
														}
														// Where there is no need to create a new row , there is a row existing at packagereport
														else {
															packageID = respond.get(2).toString();
															message.clear();
															respond.clear();
															message.add("updateNewPackageReport");
															message.add(OrderIDAtextPane.getText().toString()); // orderID
															message.add(dateIsSetA);
															message.add(quantityToPackA);
															message.add(employeeComboBoxA.getSelectedItem().toString());
															message.add("1");
															message.add(packageID);
				
															respond = myRPCClient.call(message);
															if(respond.get(1).toString().equalsIgnoreCase("valid"))
															{
																JOptionPane.showMessageDialog(myPackagingFrame, "בוצעה אריזה");
																respond.clear();
																message.clear();
																message.add("getOrderIDQuantity");
																message.add(OrderIDAtextPane.getText().toString());
																message.add("1");
																respond = myRPCClient.call(message);
																if(respond.get(1).toString().equalsIgnoreCase("valid"))
																{
																	totalQuantityA.setText(respond.get(2).toString());
																}else{
																	//something is wrong
																}
															}
															else
															{
																JOptionPane.showMessageDialog(myPackagingFrame, "לא בוצעה אריזה"); 
															}
															
															jtf_quantityToPackA.setText("");
															datePickerA.getJFormattedTextField().setText("");
															quantityToPackA=null;
															//dateIsSetA=null;
															commentsTextAreaA.setText("");
														}
													}
													catch(Exception e)
													{
														//e.printStackTrace();
													}
												}
										else
										{
											JOptionPane.showMessageDialog(myPackagingFrame, "הוזן ערך שגוי!", "שגיאה", JOptionPane.ERROR_MESSAGE);
										}
									}
									else
									{
										JOptionPane.showMessageDialog(myPackagingFrame, "ערך שגוי / גדול מסהכ הכמות", "שגיאת אריזה", JOptionPane.ERROR_MESSAGE);
									}
								}
							}
							// If radioB is pressed
							else{
								dateIsSetB = datePickerB.getJFormattedTextField().getText().toString();
								if((dateIsSetB == null) || (quantityToPackB == null) || (dateIsSetB.equalsIgnoreCase("")) || quantityToPackB.equals("") )
								{
									JOptionPane.showMessageDialog(myPackagingFrame, "יש למלא את כל השדות הנחוצים", "שגיאה", JOptionPane.ERROR_MESSAGE);
								}
								else
								{
									if(Services.isNumeric(quantityToPackB)==true)
									{
										int quantityToPackBINT = Integer.valueOf(quantityToPackB);
										int totalB = Integer.valueOf(totalQuantityB.getText().toString());
										if(quantityToPackBINT <= totalB && quantityToPackBINT!=0 )
										{
													message.add("checkExistingRowPackagingReport");
													message.add(OrderIDBtextPane.getText().toString()); //orderID
													message.add(employeeComboBoxB.getSelectedItem().toString()); //employee name
													message.add("2");
													try{
														respond = myRPCClient.call(message);
														if(respond.get(1).toString().equalsIgnoreCase("unvalid"))	//there is no row in packagereport ,need to create new row
														{
															//String packageID = respond.get(2).toString();
															message.clear();
															message.add("addNewPackageReport");
															message.add(OrderIDBtextPane.getText().toString()); // orderID
															message.add(dateIsSetB);
															message.add(quantityToPackB);
															message.add(employeeComboBoxB.getSelectedItem().toString());
															message.add("2");
				
															respond.clear();
															respond = myRPCClient.call(message);
															if(respond.get(1).toString().equalsIgnoreCase("valid"))
															{
																	JOptionPane.showMessageDialog(myPackagingFrame, "בוצעה אריזה"); 
																	respond.clear();
																	message.clear();
																	message.add("getOrderIDQuantity");
																	message.add(OrderIDBtextPane.getText().toString());
																	message.add("2");
																	respond = myRPCClient.call(message);
																	if(respond.get(1).toString().equalsIgnoreCase("valid"))
																	{
																		totalQuantityB.setText(respond.get(2).toString());
																	}else{
																		//something is wrong
																		//System.out.println("ERROR-src->Packaging->JTappedPanePackagingMain - getOrderIDQuantity");
																	}
																
																	jtf_quantityToPackB.setText("");
																	datePickerB.getJFormattedTextField().setText("");
																	quantityToPackB=null;
																	dateIsSetB=null;
																	commentsTextAreaB.setText("");
															}
															else
															{
																JOptionPane.showMessageDialog(myPackagingFrame, "לא בוצעה אריזה"); 
															}
														}
														// Where there is no need to create a new row , there is a row existing at packagereport
														else {
															packageID = respond.get(2).toString();
															message.clear();
															respond.clear();
															message.add("updateNewPackageReport");
															message.add(OrderIDBtextPane.getText().toString()); // orderID
															message.add(dateIsSetB);
															message.add(quantityToPackB);
																message.add(employeeComboBoxB.getSelectedItem().toString());
																message.add("2");
																message.add(packageID);
															respond = myRPCClient.call(message);
															if(respond.get(1).toString().equalsIgnoreCase("valid"))
															{
																JOptionPane.showMessageDialog(myPackagingFrame, "בוצעה אריזה");
																respond.clear();
																message.clear();
																message.add("getOrderIDQuantity");
																message.add(OrderIDBtextPane.getText().toString());
																message.add("2");
																respond = myRPCClient.call(message);
																if(respond.get(1).toString().equalsIgnoreCase("valid"))
																{
																	totalQuantityB.setText(respond.get(2).toString());
																}else{
																	//something is wrong
																}
																jtf_quantityToPackB.setText("");
																datePickerB.getJFormattedTextField().setText("");
																quantityToPackB=null;
																dateIsSetB=null;
																commentsTextAreaB.setText("");
															}
															else
																{
																	JOptionPane.showMessageDialog(myPackagingFrame, "לא בוצעה אריזה"); 
																}
															}
														}
													catch(Exception e)
													{
														//e.printStackTrace();
													}
											}
										else
										{
											JOptionPane.showMessageDialog(myPackagingFrame, "הוזן ערך שגוי!", "שגיאה", JOptionPane.ERROR_MESSAGE);
										}
										}
									else
									{
										JOptionPane.showMessageDialog(myPackagingFrame, "ערך שגוי / גדול מסהכ הכמות", "שגיאת אריזה", JOptionPane.ERROR_MESSAGE);
									}
								}
								
							}
							
							
						}
						else if(comboBoxOperationToDo.getSelectedItem().toString().equalsIgnoreCase("פסילה"))
						{
							if(radioA.isSelected())
							{
								dateIsSetA = datePickerA.getJFormattedTextField().getText().toString();
								if(dateIsSetA == null || dateIsSetA.equalsIgnoreCase("") || quantityToPackA==null || quantityToPackA.equals("") )
								{
									JOptionPane.showMessageDialog(myPackagingFrame, "יש למלא את כל השדות הנחוצים", "פסילה", JOptionPane.ERROR_MESSAGE);
								}
								else{
									if(Services.isNumeric(quantityToPackA)==true)
									{
										int quantityToPackAINT = Integer.valueOf(quantityToPackA);
										int totalA = Integer.valueOf(totalQuantityA.getText().toString());
										if(quantityToPackAINT <= totalA && quantityToPackAINT!=0)
										{
												//TO DO
												ArrayList<Object>message1= new ArrayList<>();
												ArrayList<Object>respond1= new ArrayList<>();
												message1.add("discardPackage");
												message1.add(OrderIDAtextPane.getText().toString()); //orderID
												message1.add(quantityToPackA);
												message1.add(commentsTextAreaA.getText().toString());
												try
												{
													respond1 = myRPCClient.call(message1);
												}
												catch(Exception e)
												{
													//e.printStackTrace();
												//	System.out.print("ERROR - src->Package->JTapppedPanePackagingMain -> פסילה");
												}
												if(respond1.get(1).toString().equalsIgnoreCase("valid"))
												{
													JOptionPane.showMessageDialog(myPackagingFrame, "דיווח על פסילה בוצע בהצלה!", "דיווח על פסילה", JOptionPane.INFORMATION_MESSAGE);
													respond1.clear();
													message1.clear();
													message1.add("getOrderIDQuantity");
													message1.add(OrderIDAtextPane.getText().toString());
													message1.add("1");
													try {
														respond1 = myRPCClient.call(message1);
													} catch (Exception e) {
														// TODO Auto-generated catch block
														//e.printStackTrace();
													}
													if(respond1.get(1).toString().equalsIgnoreCase("valid"))
													{
														totalQuantityA.setText(respond1.get(2).toString());
														
													}else{
														//something is wrong
													}
													// After adding discards , the total quantity needs to be updated on both sides.
													respond1.clear();
													message1.clear();
													message1.add("getOrderIDQuantity");
													message1.add(OrderIDBtextPane.getText().toString());
													message1.add("2");
													try {
														respond1 = myRPCClient.call(message1);
													} catch (Exception e) {
														// TODO Auto-generated catch block
														//e.printStackTrace();
													}
													if(respond1.get(1).toString().equalsIgnoreCase("valid"))
													{
														totalQuantityB.setText(respond1.get(2).toString());
														
													}else{
														//something is wrong
													}
													jtf_quantityToPackA.setText("");
													datePickerA.getJFormattedTextField().setText("");
													quantityToPackA=null;
													//dateIsSetA=null;
													commentsTextAreaA.setText("");
												}
												else
												{
													JOptionPane.showMessageDialog(myPackagingFrame, "ERROR - קרא לאדמינסטרטור", "ERROR", JOptionPane.ERROR_MESSAGE);
												}
										}
										else
										{
											JOptionPane.showMessageDialog(myPackagingFrame, "הוזן ערך שגוי!", "שגיאה", JOptionPane.ERROR_MESSAGE);
										}
									}
									else
									{
										JOptionPane.showMessageDialog(myPackagingFrame, "ערך שגוי / גדול מסהכ הכמות", "שגיאת אריזה", JOptionPane.ERROR_MESSAGE);
									}
	
								}
							}
							// side B is selected "Discard"
							else
							{
								dateIsSetB = datePickerB.getJFormattedTextField().getText().toString();
								
								if(dateIsSetB == null || dateIsSetB.equalsIgnoreCase("") || quantityToPackB==null || quantityToPackB.equals("") )
								{
									JOptionPane.showMessageDialog(myPackagingFrame, "יש למלא את כל השדות הנחוצים", "פסילה", JOptionPane.ERROR_MESSAGE);
								}
								else{
												//TO DO
									if(Services.isNumeric(quantityToPackB)==true)
									{
										int quantityToPackBINT = Integer.valueOf(quantityToPackB);
										int totalB = Integer.valueOf(totalQuantityB.getText().toString());
										if(quantityToPackBINT <= totalB && quantityToPackBINT!=0)
										{
												ArrayList<Object>message1= new ArrayList<>();
												ArrayList<Object>respond1= new ArrayList<>();
												message1.add("discardPackage");
												message1.add(OrderIDBtextPane.getText().toString()); //orderID
												message1.add(quantityToPackB);
												message1.add(commentsTextAreaB.getText().toString());
												try
												{
													respond1 = myRPCClient.call(message1);
												}
												catch(Exception e)
												{
													//e.printStackTrace();
												//	System.out.print("ERROR - src->Package->JTapppedPanePackagingMain -> פסילה");
												}
												if(respond1.get(1).toString().equalsIgnoreCase("valid"))
												{
													JOptionPane.showMessageDialog(myPackagingFrame, "דיווח על פסילה בוצע בהצלה!", "דיווח על פסילה", JOptionPane.INFORMATION_MESSAGE);
													respond1.clear();
													message1.clear();
													message1.add("getOrderIDQuantity");
													message1.add(OrderIDBtextPane.getText().toString());
													message1.add("2");
													try {
														respond1 = myRPCClient.call(message1);
													} catch (Exception e) {
														// TODO Auto-generated catch block
														//e.printStackTrace();
													}
													if(respond1.get(1).toString().equalsIgnoreCase("valid"))
													{
														totalQuantityB.setText(respond1.get(2).toString());
														
													}else{
														//something is wrong
													}
													// After Discard function , both sides needs to be updated with the total number of quantity.
													respond1.clear();
													message1.clear();
													message1.add("getOrderIDQuantity");
													message1.add(OrderIDAtextPane.getText().toString());
													message1.add("1");
													try {
														respond1 = myRPCClient.call(message1);
													} catch (Exception e) {
														// TODO Auto-generated catch block
														//e.printStackTrace();
													}
													if(respond1.get(1).toString().equalsIgnoreCase("valid"))
													{
														totalQuantityA.setText(respond1.get(2).toString());
														
													}else{
														//something is wrong
													}
													
													jtf_quantityToPackB.setText("");
													datePickerB.getJFormattedTextField().setText("");
													quantityToPackB=null;
													dateIsSetB=null;
													commentsTextAreaB.setText("");
												}
												else
												{
													JOptionPane.showMessageDialog(myPackagingFrame, "ERROR - קרא לאדמינסטרטור", "ERROR", JOptionPane.ERROR_MESSAGE);
												}
										}
										else
										{
											JOptionPane.showMessageDialog(myPackagingFrame, "הוזן ערך שגוי!", "שגיאה", JOptionPane.ERROR_MESSAGE);
										}
									}
									else
									{
										JOptionPane.showMessageDialog(myPackagingFrame, "ערך שגוי / גדול מסהכ הכמות", "שגיאת אריזה", JOptionPane.ERROR_MESSAGE);
									}
								}
							}
						}
						//If HASHMASHA is selected to be done then :
						else if(comboBoxOperationToDo.getSelectedItem().toString().equalsIgnoreCase("השמשה"))
						{
						
							//Side A is selected (Hashmasha)
							if(radioA.isSelected())
							{
								dateIsSetA = datePickerA.getJFormattedTextField().getText().toString();
								if(dateIsSetA == null || dateIsSetA.equalsIgnoreCase("") || hashmashaTextFieldA.equals("") || hashmashaTextFieldA == null|| diopterA.equals("")|| diopterA ==null || newQuantityA.getText()=="" ||	newQuantityA.getText()==null	)
								{
									JOptionPane.showMessageDialog(myPackagingFrame, "יש למלא את כל השדות הנחוצים", "פסילה", JOptionPane.ERROR_MESSAGE);
								}
								else{
									//These variables will help for the checking input that must be numbers .
									String diopterStr = diopterA.getText().toString();
									String hashmashaStr = hashmashaTextFieldA.getText().toString();
									String newQuanStr = newQuantityA.getText().toString();
									if( Services.isNumeric(diopterStr)==true && Services.isNumeric(hashmashaStr)==true && Services.isNumeric(newQuanStr)==true )
									{
										int newQuantity = Integer.valueOf(newQuantityA.getText().toString());
										int totalA = Integer.valueOf(totalQuantityA.getText().toString());
										if(newQuantity <= totalA && newQuantity!=0)
										{
									
												//To DO 
												int newQuantityAINT = Integer.valueOf(newQuantityA.getText().toString());
												int totalQuantityAINT = Integer.valueOf(totalQuantityA.getText().toString());
												if(newQuantityAINT > totalQuantityAINT || newQuantityAINT== 0)
												{
													JOptionPane.showMessageDialog(myPackagingFrame, "אנא בחר כמות חדשה פחות מהכמות הכללית");
												}
												else
												{
													ArrayList<Object>message1= new ArrayList<>();
													ArrayList<Object>respond1= new ArrayList<>();
													message1.add("createNewOrderhashmasha");
													String newOrderID = hashmashaTextFieldA.getText().toString();
													message1.add(newOrderID); // new OrderID
													message1.add(typeA.getSelectedItem().toString());
													message1.add(diopterA.getText().toString());
													// Today's Date
													DateFormat today = new SimpleDateFormat("yyyy/MM/dd");
													Calendar cal = Calendar.getInstance(); // cal holds the day of current day .
												    message1.add(today.format(cal.getTime()));//Today's Date is entered.
												    // 
												    message1.add(newQuantityA.getText().toString());
												    message1.add("7");
												    try
												    {
												    	respond1 = myRPCClient.call(message1);
												    }
												    catch(Exception e)
												    {
												    	//e.printStackTrace();
												    //	System.out.println("ERROR - src->Package->JTappedPanePAckagingMain-> createNewOrderhashmasha()");
												    }
												    if(respond1.get(1).toString().equalsIgnoreCase("valid"))
												    {
														//Creating a new packagehashmasha new row after creating new orderID .
														message.clear();
												    	respond.clear();
												    	message.add("createNewPackageHashmasha");
												    	message.add(OrderIDAtextPane.getText().toString()); 	//Original orderID
												    	message.add(newOrderID);								//New entered orderID
												    	message.add(commentsTextAreaA.getText().toString());	//User comments
												    	try{
												    		respond = myRPCClient.call(message);
												    	}catch(Exception e)
												    	{
												    		//e.printStackTrace();
												    	//	System.out.println("ERROR - src->Packaging->JTappedPanePackagingMain(createNewPackageHashmasha)");
												    		
												    	}
												    	if(respond.get(1).toString().equalsIgnoreCase("valid"))
												    	{
												    		JOptionPane.showMessageDialog(myPackagingFrame, "השמשה בוצעה בהצלחה!");
												    	}else
												    	{
												    		JOptionPane.showMessageDialog(myPackagingFrame, "הפעולה השתבשה , לא ליצור קשר עם האדמינסטרטור");
												    		//System.out.println("ERROR - src->Packaging->JTappedPanePackagingMain(createNewPackageHashmasha)");
												    	}
												    	//Refreshing the Total quantity
												    	respond1.clear();
														message1.clear();
														message1.add("getOrderIDQuantity");
														message1.add(OrderIDAtextPane.getText().toString());
														message1.add("1");
														try {
															respond1 = myRPCClient.call(message1);
														} catch (Exception e) {
															// TODO Auto-generated catch block
															//e.printStackTrace();
														}
														if(respond1.get(1).toString().equalsIgnoreCase("valid"))
														{
															totalQuantityA.setText(respond1.get(2).toString());
															
														}else{
														//	System.out.println("ERROR - src->Packaging->JTappedPanePackagingMain(createNewPackageHashmasha) -  couldnt update total quantity A");
														}
														//After Hashmasha , side B's total quantity needs to be updated too .
														respond1.clear();
														message1.clear();
														message1.add("getOrderIDQuantity");
														message1.add(OrderIDBtextPane.getText().toString());
														message1.add("2");
														try {
															respond1 = myRPCClient.call(message1);
														} catch (Exception e) {
															// TODO Auto-generated catch block
															//e.printStackTrace();
														}
														if(respond1.get(1).toString().equalsIgnoreCase("valid"))
														{
															totalQuantityB.setText(respond1.get(2).toString());
															
														}else{
														//	System.out.println("ERROR - src->Packaging->JTappedPanePackagingMain(createNewPackageHashmasha) -  couldnt update total quantity B");
														}
												    }
												    
												    else
												    {
												    	JOptionPane.showMessageDialog(myPackagingFrame, "בעיה בהזנת נתונים לבסיס הנתונים - יתכן וכי המספר פקע שהוכנה כבר קיים");
												    //	System.out.println("ERROR - src->Packaging->JTappedPanePackagingMain(hashmasha)");
												    }
												    //Question regarding cleaning celles
												    int answer = JOptionPane.showConfirmDialog(myPackagingFrame, "האם לנקות שדות הזנה?", "ניקוי שדות", JOptionPane.YES_NO_OPTION);
												    if(answer == 0)
												    {
												    	diopterA.setText("");
												    	hashmashaTextFieldA.setText("");
												    	newQuantityA.setText("");
												    }
												}
										}
										else
										{
											JOptionPane.showMessageDialog(myPackagingFrame, "הוזן ערך שגוי!", "שגיאה", JOptionPane.ERROR_MESSAGE);
										}
									}
									else
									{
										JOptionPane.showMessageDialog(myPackagingFrame, "ערך שגוי / גדול מסהכ הכמות", "שגיאת אריזה", JOptionPane.ERROR_MESSAGE);
									}
								}
									
								
							}
							
							// Side b selected (Hashmasha)
							else
							{
								dateIsSetB = datePickerB.getJFormattedTextField().getText().toString();
								if(dateIsSetB == null || dateIsSetB.equalsIgnoreCase("") || hashmashaTextFieldB.equals("") || hashmashaTextFieldB == null|| diopterA.equals("")|| diopterB ==null || newQuantityB.getText()=="" ||	newQuantityB.getText()==null		)
								{
									JOptionPane.showMessageDialog(myPackagingFrame, "יש למלא את כל השדות הנחוצים", "פסילה", JOptionPane.ERROR_MESSAGE);
								}
								else{
									//To DO
														String diopterStrB = diopterB.getText().toString();
														String hashmashaStrB = hashmashaTextFieldB.getText().toString();
														String newQuanStrB = newQuantityB.getText().toString();
														if( Services.isNumeric(diopterStrB)==true && Services.isNumeric(hashmashaStrB)==true && Services.isNumeric(newQuanStrB)==true )
														{
															int newQuantity = Integer.valueOf(newQuantityB.getText().toString());
															int totalB = Integer.valueOf(totalQuantityB.getText().toString());
															if(newQuantity <= totalB && newQuantity!=0)
															{
																	int newQuantityBINT = Integer.valueOf(newQuantityB.getText().toString());
																	int totalQuantityBINT = Integer.valueOf(totalQuantityB.getText().toString());
																	if(newQuantityBINT > totalQuantityBINT || newQuantityBINT==0)
																	{
																		JOptionPane.showMessageDialog(myPackagingFrame, "אנא בחר כמות חדשה פחות מהכמות הכללית");
																	}
																	else{
																		ArrayList<Object>message1= new ArrayList<>();
																		ArrayList<Object>respond1= new ArrayList<>();
																		message1.add("createNewOrderhashmasha");
																		String newOrderID = hashmashaTextFieldB.getText().toString();
																		message1.add(newOrderID); // new OrderID
																		message1.add(typeB.getSelectedItem().toString());
																		message1.add(diopterB.getText().toString());
																		// Today's Date
																		DateFormat today = new SimpleDateFormat("yyyy/MM/dd");
																		Calendar cal = Calendar.getInstance(); // cal holds the day of current day .
																	    message1.add(today.format(cal.getTime()));//Today's Date is entered.
																	    // 
																	    message1.add(newQuantityB.getText().toString());
																	    message1.add("7");
																	    try
																	    {
																	    	respond1 = myRPCClient.call(message1);
																	    }
																	    catch(Exception e)
																	    {
																	    	//e.printStackTrace();
																	    	//System.out.println("ERROR - src->Package->JTappedPanePAckagingMain-> createNewOrderhashmasha()");
																	    }
																	    if(respond1.get(1).toString().equalsIgnoreCase("valid"))
																	    {
																			//Creating a new packagehashmasha new row after creating new orderID .
																			message.clear();
																	    	respond.clear();
																	    	message.add("createNewPackageHashmasha");
																	    	message.add(OrderIDBtextPane.getText().toString()); 	//Original orderID
																	    	message.add(newOrderID);								//New entered orderID
																	    	message.add(commentsTextAreaB.getText().toString());	//User comments
																	    	try{
																	    		respond = myRPCClient.call(message);
																	    	}catch(Exception e)
																	    	{
																	    		//e.printStackTrace();
																	    	//	System.out.println("ERROR - src->Packaging->JTappedPanePackagingMain(createNewPackageHashmasha)");
																	    		
																	    	}
																	    	if(respond.get(1).toString().equalsIgnoreCase("valid"))
																	    	{
																	    		JOptionPane.showMessageDialog(myPackagingFrame, "השמשה בוצעה בהצלחה!");
																	    	}else
																	    	{
																	    		JOptionPane.showMessageDialog(myPackagingFrame, "הפעולה השתבשה , לא ליצור קשר עם האדמינסטרטור");
																	   // 		System.out.println("ERROR - src->Packaging->JTappedPanePackagingMain(createNewPackageHashmasha)");
																	    	}
																	    	//Refreshing the Total quantity
																	    	respond1.clear();
																			message1.clear();
																			message1.add("getOrderIDQuantity");
																			message1.add(OrderIDAtextPane.getText().toString());
																			message1.add("1");
																			try {
																				respond1 = myRPCClient.call(message1);
																			} catch (Exception e) {
																				// TODO Auto-generated catch block
																				//e.printStackTrace();
																			}
																			if(respond1.get(1).toString().equalsIgnoreCase("valid"))
																			{
																				totalQuantityA.setText(respond1.get(2).toString());
																				
																			}else{
																			//	System.out.println("ERROR - src->Packaging->JTappedPanePackagingMain(createNewPackageHashmasha) -  couldnt update total quantity A");
																			}
																			//After Hashmasha , side B's total quantity needs to be updated too .
																			respond1.clear();
																			message1.clear();
																			message1.add("getOrderIDQuantity");
																			message1.add(OrderIDBtextPane.getText().toString());
																			message1.add("2");
																			try {
																				respond1 = myRPCClient.call(message1);
																			} catch (Exception e) {
																				// TODO Auto-generated catch block
																				//e.printStackTrace();
																			}
																			if(respond1.get(1).toString().equalsIgnoreCase("valid"))
																			{
																				totalQuantityB.setText(respond1.get(2).toString());
																				
																			}else{
																				//System.out.println("ERROR - src->Packaging->JTappedPanePackagingMain(createNewPackageHashmasha) -  couldnt update total quantity B");
																			}
																	    }
																	    
																	    else
																	    {
																	    	JOptionPane.showMessageDialog(myPackagingFrame, "בעיה בהזנת נתונים לבסיס הנתונים - יתכן וכי המספר פקע שהוכנה כבר קיים");
																	    //	System.out.println("ERROR - src->Packaging->JTappedPanePackagingMain(hashmasha)");
																	    }
																	    //Question regarding cleaning celles
																	    int answer = JOptionPane.showConfirmDialog(myPackagingFrame, "האם לנקות שדות הזנה?", "ניקוי שדות", JOptionPane.YES_NO_OPTION);
																	    if(answer == 0)
																	    {
																	    	diopterB.setText("");
																	    	hashmashaTextFieldB.setText("");
																	    	newQuantityB.setText("");
																	    }
																	}
															}
															else
															{
																JOptionPane.showMessageDialog(myPackagingFrame, "הוזן ערך שגוי!", "שגיאה", JOptionPane.ERROR_MESSAGE);
															}
														}
														else
														{
															JOptionPane.showMessageDialog(myPackagingFrame, "ערך שגוי / גדול מסהכ הכמות", "שגיאת אריזה", JOptionPane.ERROR_MESSAGE);
														}
								}
							}
						}
						else if(comboBoxOperationToDo.getSelectedItem().toString().equalsIgnoreCase("סיום אריזה"))
						{
							if(totalQuantityA.getText().equals("0") && totalQuantityB.getText().equals("0"))
							{
								ArrayList<Object>messageFinish = new ArrayList<>();
								ArrayList<Object>respondFinish = new ArrayList<>();
								messageFinish.add("finishPackaging");
								messageFinish.add(OrderIDAtextPane.getText().toString());
								try
								{
									respondFinish=myRPCClient.call(messageFinish);
								}
								catch(Exception e)
								{
									//e.printStackTrace();
									//System.out.println("ERROR - src->Packaging->JTappedPanelPackagingMain(finishPackaging)->Back from server couldnt finish packaging orderID : '"+ OrderIDAtextPane.getText().toString() +"'");
								}
								if(respondFinish.get(1).toString().equalsIgnoreCase("valid"))
								{
									JOptionPane.showMessageDialog(myPackagingFrame, "פעולת סיום אריזה בוצעה בהצלחה!", "סיום אריזה", JOptionPane.INFORMATION_MESSAGE);
									try{
										message.clear();
										respond.clear();
										myPackagingCleint = new RPCClient();
										message.add("initializePackageMailPanelVariables");
										respond = myPackagingCleint.call(message);
										if(respond.get(1).toString().equalsIgnoreCase("valid"))
										{
											setVairables(respond);
										}
										else
										{
											model.setRowCount(0);
										}
									}catch(Exception e)
									{
										//e.printStackTrace();
									}
									myJTappedPane.setSelectedIndex(0);
								}
								else
								{
									JOptionPane.showMessageDialog(myPackagingFrame, "פעולת סיום אריזה נכשלה!!", "סיום אריזה", JOptionPane.ERROR_MESSAGE);
								}
								
							}
							else
								JOptionPane.showMessageDialog(myPackagingFrame, "ניתן לסיים אריזה רק בסיום אריזה א ואריזה ב", "סיום שלב האריזה", JOptionPane.ERROR_MESSAGE);
							finishPackagingChlicked=true;
						}
				//General Check after clicking approve , to suggest finishing the packaging if the both totals are 0.
				int totalA = Integer.valueOf(totalQuantityA.getText().toString()); 
				int totalB = Integer.valueOf(totalQuantityB.getText().toString());
				if(finishPackagingChlicked==false)
				{
						if(totalA <= 0 && totalB <=0)
						{
							int answer;
		 					answer = JOptionPane.showConfirmDialog(myPackagingFrame, "האם ברצונך לסיים את שלב האריזה עבור פקע זו?", "סיום שלב האריזה", JOptionPane.YES_NO_OPTION);
								if(answer == 0)
								{
									ArrayList<Object>messageFinish = new ArrayList<>();
									ArrayList<Object>respondFinish = new ArrayList<>();
									messageFinish.add("finishPackaging");
									messageFinish.add(OrderIDAtextPane.getText().toString());
									try
									{
										respondFinish=myRPCClient.call(messageFinish);
									}
									catch(Exception e)
									{
										//e.printStackTrace();
										//System.out.println("ERROR - src->Packaging->JTappedPanelPackagingMain(finishPackaging)->Back from server couldnt finish packaging orderID : '"+ OrderIDAtextPane.getText().toString() +"'");
									}
									if(respondFinish.get(1).toString().equalsIgnoreCase("valid"))
									{
										JOptionPane.showMessageDialog(myPackagingFrame, "פעולת סיום אריזה בוצעה בהצלחה!", "סיום אריזה", JOptionPane.INFORMATION_MESSAGE);
										try{
											message.clear();
											respond.clear();
											myPackagingCleint = new RPCClient();
											message.add("initializePackageMailPanelVariables");
											respond = myPackagingCleint.call(message);
											if(respond.get(1).toString().equalsIgnoreCase("valid"))
											{
												setVairables(respond);
											}
											else
											{
												model.setRowCount(0);
											}
										}catch(Exception e)
										{
											//e.printStackTrace();
										}
										myJTappedPane.setSelectedIndex(0);
									}
									else
									{
										JOptionPane.showMessageDialog(myPackagingFrame, "פעולת סיום אריזה נכשלה!!", "סיום אריזה", JOptionPane.ERROR_MESSAGE);
									}
								}
							}
				}else{
					finishPackagingChlicked=false;
				}
				if(totalA <0 )
				{
					totalQuantityA.setText("0");
				}
				if(totalB < 0)
				{
					totalQuantityB.setText("0");
				}
					}
				});
		
		
		radioA.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if(radioA.isSelected())
					radioB.setSelected(false);
				else
					radioB.setSelected(true);
			}
		});
		
		JPanel panel_3 = new JPanel(){@Override
			public void paintComponent(Graphics g) {
	        Graphics2D g2d = (Graphics2D) g;
	        Color color1 = getBackground();
	        Color color2 = color1.darker();
	        int w = getWidth();
	        int h = getHeight(); 
	        GradientPaint gp = new GradientPaint(
	                0, 0, color1,
	                0, h, color2);

	        g2d.setPaint(gp);
	        g2d.fillRect(0, 0, w, h);
	        }};
		panel_3.setBackground(new Color(173, 216, 230));
		panel_3.setBorder(new TitledBorder(null, "\u05D0\u05E8\u05D9\u05D6\u05D4 \u05D0", TitledBorder.CENTER, TitledBorder.TOP, null, null));
		panel_1.add(panel_3, "cell 3 1,alignx center,growy");
		try{
			ArrayList<Object>message = new ArrayList<>();
			ArrayList<Object>respond = new ArrayList<>();
			message.add("getPackageEmployeesNames");
			respond = myRPCClient.call(message);
			message.clear();
			if(respond.get(1).toString().equalsIgnoreCase("valid"))
				setEmployeeComboBoxes(respond);
		}
		catch(Exception e)
		{
			//e.printStackTrace();
		}
		panel_3.setLayout(new MigLayout("", "[grow][][][grow]", "[14px][20px][14px][23px][14px][19px][20px][43px,grow][grow][][]"));
		
		JLabel label_6 = new JLabel("מספר פק\"ע:");
		panel_3.add(label_6, "cell 2 1,alignx left,aligny bottom");
		
		jtf_quantityToPackA = new TextField();
		jtf_quantityToPackA.addTextListener(new TextListener() {
			public void textValueChanged(TextEvent e) {
				quantityToPackA = jtf_quantityToPackA.getText().toString();
			//	System.out.println("jtf_quantityToPackA is : '"+quantityToPackA+"'");
			}
		});
		
		datePickerA = new JDatePickerImpl(endPanel, new DateLabelFormatter());
		datePickerA.setBackground(new Color(173, 216, 230));
		datePickerA.getJFormattedTextField().addPropertyChangeListener(new PropertyChangeListener() {
			public void propertyChange(PropertyChangeEvent arg0) {
				dateIsSetA = datePickerA.getJFormattedTextField().getText().toString();
			//	System.out.println("Property changed - dateIsSetA :'"+dateIsSetA+"'");
			}
		});
		datePickerA.getJFormattedTextField().setHorizontalAlignment(SwingConstants.CENTER);
		panel_3.add(datePickerA, "cell 1 2,growx,aligny top");
		
		JLabel label_17 = new JLabel("תאריך אריזה:");
		panel_3.add(label_17, "cell 2 2,alignx left,aligny top");
		
		JLabel label_9 = new JLabel("סה\"כ  /   כמה");
		label_9.setHorizontalAlignment(SwingConstants.CENTER);
		panel_3.add(label_9, "cell 1 4,alignx center,aligny top");
		
		JLabel label_7 = new JLabel("ארזתי\\פסלתי:\r\n");
		panel_3.add(label_7, "cell 2 4,alignx left,aligny top");
		panel_3.add(jtf_quantityToPackA, "flowx,cell 1 5,alignx center");
		
		JLabel label_12 = new JLabel("/");
		label_12.setHorizontalAlignment(SwingConstants.CENTER);
		panel_3.add(label_12, "cell 1 5,alignx right,aligny top");
		
		totalQuantityA = new TextField();
		totalQuantityA.setEditable(false);
		panel_3.add(totalQuantityA, "cell 1 5,alignx center,aligny top");
		
		
		
		employeeComboBoxA.addPropertyChangeListener(new PropertyChangeListener() {
			public void propertyChange(PropertyChangeEvent evt) {
				if(employeeComboBoxA.getSelectedItem()!=null)
				{
					employeeNameSelectedA = employeeComboBoxA.getSelectedItem().toString();
					//System.out.println("employeeComboBoxA is : '"+employeeNameSelectedA+"'");
				}
			}
		});
		panel_3.add(employeeComboBoxA, "cell 1 6,alignx right,aligny top");
		
		JLabel label_13 = new JLabel("עובד:");
		label_13.setHorizontalAlignment(SwingConstants.CENTER);
		panel_3.add(label_13, "cell 2 6,alignx left,aligny top");
		
		JScrollPane scrollPane_1 = new JScrollPane();
		panel_3.add(scrollPane_1, "cell 1 7,grow");
		
		commentsTextAreaA = new JTextArea();
		commentsTextAreaA.setEnabled(false);
		commentsTextAreaA.setWrapStyleWord(true);
		scrollPane_1.setViewportView(commentsTextAreaA);
		commentsTextAreaA.setText("הערות להשמשה/פסילה");
		
		JLabel label_15 = new JLabel("הערות:");
		panel_3.add(label_15, "cell 2 7,aligny top");
		
		OrderIDAtextPane = new JTextPane();
		OrderIDAtextPane.setEditable(false);
		OrderIDAtextPane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
		panel_3.add(OrderIDAtextPane, "cell 1 1,alignx center,aligny top");
		
		JPanel panel_5 = new JPanel(){@Override
			public void paintComponent(Graphics g) {
	        Graphics2D g2d = (Graphics2D) g;
	        Color color1 = getBackground();
	        Color color2 = color1.darker();
	        int w = getWidth();
	        int h = getHeight(); 
	        GradientPaint gp = new GradientPaint(
	                0, 0, color1,
	                0, h, color2);

	        g2d.setPaint(gp);
	        g2d.fillRect(0, 0, w, h);
	        }};
		panel_5.setBackground(new Color(173, 216, 230));
		panel_5.setBorder(new TitledBorder(null, "\u05D4\u05E9\u05DE\u05E9\u05D4", TitledBorder.RIGHT, TitledBorder.TOP, null, null));
		panel_3.add(panel_5, "cell 1 10,grow");
		panel_5.setLayout(new MigLayout("", "[][][][][grow][grow][grow][grow][]", "[][][][]"));
		
		hashmashaTextFieldA = new JTextField();
		panel_5.add(hashmashaTextFieldA, "cell 0 0 8 1,growx");
		hashmashaTextFieldA.setColumns(10);
		hashmashaTextFieldA.setEnabled(false);
		JLabel lblNewLabel = new JLabel("מספר פקע חדש להשמשה:");
		panel_5.add(lblNewLabel, "cell 8 0");
		
		typeA = new JComboBox();
		panel_5.add(typeA, "cell 1 1 7 1,growx");
		typeA.setEnabled(false);
		JLabel label_22 = new JLabel("סוג:");
		panel_5.add(label_22, "cell 8 1");
		
		newQuantityA = new JTextField();
		newQuantityA.setEnabled(false);
		panel_5.add(newQuantityA, "cell 0 2 8 1,growx");
		newQuantityA.setColumns(10);
		
		JLabel label_24 = new JLabel("כמות:");
		panel_5.add(label_24, "cell 8 2");
		
		diopterA = new JTextField();
		panel_5.add(diopterA, "cell 0 3 8 1,growx");
		diopterA.setColumns(10);
		diopterA.setEnabled(false);
		
		JLabel label_26 = new JLabel("דיופטר:");
		panel_5.add(label_26, "cell 8 3");
		
		JButton button_3 = new JButton("חזרה");
		button_3.setIcon(new ImageIcon(JTappedPanePackagingMain.class.getResource("/graphics/back.png")));
		panel_1.add(button_3, "cell 2 3,alignx center");
		button_3.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				myJTappedPane.setSelectedIndex(0);
			}
		});
		
		//Initialize the A\B types comboboxes :
		ArrayList<Object>message2 = new ArrayList<>();
		ArrayList<Object>respond2 = new ArrayList<>();
		try{
			
			message2.add("getListOfProducts");
			respond2 = myRPCClient.call(message2);
			//System.out.println(respond2.get(1).toString());
			Iterator itr = respond2.iterator();
			itr.next();itr.next();
			while(itr.hasNext())
			{
				String str = itr.next().toString();
				typeA.addItem(str);
				typeB.addItem(str);
			}
		}
		catch(Exception e)
		{
			//e.printStackTrace();
		}
		

		
		//Part of the Initializing proccess :
		try{
			ArrayList<Object>message = new ArrayList<>();
			ArrayList<Object>respond = new ArrayList<>();
			myPackagingCleint = new RPCClient();
			message.add("initializePackageMailPanelVariables");
			respond = myPackagingCleint.call(message);
			if(respond.get(1).toString().equalsIgnoreCase("valid"))
			{
				setVairables(respond);
			}
			else
			{
			//	System.out.println("no GOOD");
			}
		}catch(Exception e)
		{
			//e.printStackTrace();
		}
		
		startmodel.setSelected(true);
		endmodel.setSelected(true);
	}
/**
 * This method sets the variables on the current panel , order Id's 	
 * @param respond
 */
	public void setVairables(ArrayList<Object> respond) {
		
		Iterator<Object>itr = respond.iterator();
		model.setRowCount(0);
		itr.next();itr.next(); // passed the first 2 non needed values.
			while(itr.hasNext())
			{
				//PolishReportEntity myEntity =(PolishReportEntity) itr.next();
				model.addRow(new Object[]{itr.next()});
			}
		}
/**
 * This method gets from the DB the employee's of packaging department and initializes the employee's comboboxes	
 * @param message
 */
	public void setEmployeeComboBoxes(ArrayList<Object> message)
	{
		
		for (int i = 2; i<message.size(); i++)
		{
			//System.out.println(message.get(i).toString());
			employeeComboBoxA.addItem(message.get(i));
			employeeComboBoxB.addItem(message.get(i));
		}
			
	/*	
		Iterator<Object>itr = message.iterator();
		Iterator<Object>itr1 = message.iterator();
		itr.next();itr.next();itr1.next();itr1.next();
		while(itr.hasNext()&& itr1.hasNext())
		{
			employeeComboBoxA.addItem(itr.next());
			employeeComboBoxB.addItem(itr1.next());
		}
		*/
	}
}
